package com.wawei.seeds.me;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.wawei.seeds.R;
import com.wawei.seeds.SeedsApp;
import com.wawei.seeds.adapter.SeedsBaseAdapter;
import com.wawei.seeds.common.ClipImageActivity;
import com.wawei.seeds.model.HeroInfo;
import com.wawei.seeds.model.WalnutMainEvent;
import com.wawei.seeds.services.ServiceHandler;
import com.wawei.seeds.services.WalnutPortraitServiceHandler;
import com.wawei.seeds.utils.ImageLoader;
import com.wawei.seeds.utils.PrefUtils;
import com.wawei.seeds.utils.RetrofitNetworkService;
import com.wawei.seeds.utils.WalnutBaseNofityHandler;

import java.io.File;
import java.util.List;

import butterknife.InjectView;
import retrofit.RestAdapter;
import retrofit.mime.TypedFile;

/**
 * Created by t27891 on 15/7/2.
 */
public class MeSelfPortraitFragment extends MeBaseFragment {
    @InjectView(R.id.walnut_hero_head)
    ImageView headImage;
    @InjectView(R.id.item_self_portrait_name)
    TextView meAlias;
    @InjectView(R.id.item_self_portrait_gender)
    TextView meGender;
    @InjectView(R.id.item_header_part)View headerView;

    private MeSelfPortraitNotifyHandler notifyHandler;
    private WalnutPortraitServiceHandler serviceHandler;
    private ImageLoader imageLoader;

    public static final int UPLOAD_HEADER_IMAGE = 0x9003;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        notifyHandler = new MeSelfPortraitNotifyHandler(this);
        serviceHandler = new WalnutPortraitServiceHandler(getActivity());
        imageLoader = new ImageLoader(getActivity(), R.drawable.walnut_logo);
    }

    @Override
    public View onCreateViewBeforeInjection(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_walnut_myself, container, false);
    }

    @Override
    public void onCreateViewAfterInjection(View view, LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    }

    @Override
    public void onViewCreatedAfterTitle(final View view, Bundle savedInstanceState) {
        RestAdapter restAdapter = RetrofitNetworkService.makeAsyncRestAdapter();
        Bundle bundle = new Bundle();
        bundle.putInt(WalnutPortraitServiceHandler.PORTRAIT_WHO, PrefUtils.getUserId(getActivity()));
        serviceHandler.retrieveData(restAdapter, bundle, notifyHandler, WalnutBaseNofityHandler.INIT_ACHIEVE_DATA);

        headerView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new PhotoPopupWindow(getActivity(), view);
            }
        });
    }

    @Override
    public String getTitle() {
        return getString(R.string.walnut_me_personal_info);
    }

    @Override
    public ServiceHandler makeServiceHandler() {
        return null;
    }

    @Override
    public SeedsBaseAdapter<WalnutMainEvent> makeListAdapter() {
        return null;
    }

    @Override
    public Bundle makeConditionBundle(int phase) {
        return null;
    }

    @Override
    public Intent makeIntent4ListItemClicked(AdapterView<?> parent, View view, int position, long id, Object itemData) {
        return null;
    }

    private static class MeSelfPortraitNotifyHandler extends WalnutBaseNofityHandler<MeSelfPortraitFragment, HeroInfo> {
        public MeSelfPortraitNotifyHandler(MeSelfPortraitFragment meSelfPortraitFragment) {
            super(meSelfPortraitFragment);
        }

        @Override
        public void doInitData(MeSelfPortraitFragment meSelfPortraitFragment, List<HeroInfo> data) {
            HeroInfo hero = null;
            if (null != data && data.size() > 0) {
                hero = data.get(0);
            }

            if (hero == null) {
                SeedsApp app = (SeedsApp) get().getActivity().getApplication();
                hero = (HeroInfo) app.getSession().get(SeedsApp.LOGIN_USER);
            }

            if (hero != null) {
                get().meAlias.setText(hero.alias);
                get().meGender.setText(hero.gender);
                get().imageLoader.loadImage(hero.headPortrait, get().headImage, true, false);
            }
        }

        @Override
        public void handleOtherMessage(Message msg) {
            super.handleOtherMessage(msg);

            Bundle bundle = msg.getData();
            switch (msg.what) {
                case UPLOAD_HEADER_IMAGE:
                    String url = (String)bundle.get(RetrofitNetworkService.RESULT_DATA);
                    if (url != null) {
                        SeedsApp app = (SeedsApp) get().getActivity().getApplication();
                        HeroInfo me = (HeroInfo) app.getSession().get(SeedsApp.LOGIN_USER);
                        if (me != null) {
                            me.headPortrait = url;
                            app.getSession().put(SeedsApp.LOGIN_USER, me);
                        }
                        Toast.makeText(get().getActivity(), "上传头像成功", Toast.LENGTH_LONG).show();
                    } else  {
                        Toast.makeText(get().getActivity(), "上传头像失败", Toast.LENGTH_LONG).show();
                    }
                    break;
            }
        }
    }

    class PhotoPopupWindow extends PopupWindow {
        private Context context;

        public PhotoPopupWindow(Context context, View parent) {
            super(context);

            this.context = context;
            // 加载窗口对应的视图
            View view = View.inflate(context, R.layout.popupwindow_photo, null);
            // 设置显示动画
            view.startAnimation(AnimationUtils.loadAnimation(context, R.anim.abc_fade_in));
            LinearLayout ll_popup = (LinearLayout) view.findViewById(R.id.ll_popup);
            ll_popup.startAnimation(AnimationUtils.loadAnimation(context, R.anim.push_bottom_in));
            // 设置宽高
            setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
            setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
            // 设置窗口背景
            setBackgroundDrawable(new BitmapDrawable());
            //
            setFocusable(true);
            setOutsideTouchable(true);
            setContentView(view);
            showAtLocation(parent, Gravity.BOTTOM, 0, 0);

            update();

            Button buttonCamera = (Button) view.findViewById(R.id.item_popupwindows_camera);
            Button buttonCancel = (Button) view.findViewById(R.id.item_popupwindows_cancel);
            Button buttonAlbum = (Button) view.findViewById(R.id.item_popupwindows_photo);

            buttonCamera.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    photo();
                    dismiss();
                }
            });
            buttonAlbum.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startAlbum();
                    dismiss();
                }
            });
            buttonCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                }
            });
        }

        public void photo() {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            // intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
            startActivityForResult(intent, TAKE_PICTURE);
             /*

            String status=Environment.getExternalStorageState();
            if(status.equals(Environment.MEDIA_MOUNTED))
            {

                //File dir=new File(Environment.getExternalStorageDirectory() + "/myimage/");
                //if(!dir.exists()) {
                //    dir.mkdirs();
                //}

                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                //File file = new File(dir, String.valueOf(System.currentTimeMillis()) + ".jpg");
                // String path = file.getPath();
                //Uri imageUri = Uri.fromFile(file);
                //intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                //intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
                // intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(context.getFilesDir(), TMP_PATH)));
                intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
                startActivityForResult(intent, TAKE_PICTURE);
            } else {
                Toast.makeText(context, "没有储存卡", Toast.LENGTH_LONG).show();
            }
            */
        }

        // 调用系统的默认的相册页面，那个啥微信的选择页面以后再做。
        private void startAlbum() {
            try {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("image/*");
                startActivityForResult(intent, ALBUM_PICTURE);
            } catch (ActivityNotFoundException e) {
                try {
                    Intent intent = new Intent(Intent.ACTION_PICK);
                    intent.setDataAndType(
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                    startActivityForResult(intent, ALBUM_PICTURE);
                } catch (Exception ex) {
                    // TODO: handle exception
                    ex.printStackTrace();
                }
            }
        }
    }



    private static final int TAKE_PICTURE = 0x000001;

    private static final int ALBUM_PICTURE = 0x000002;

    private static final int CLIP_RESULT = 0x000003;

    private static final String TMP_PATH = "clip_temp.jpg";

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case TAKE_PICTURE:
                Uri uri = data == null ? null : data.getData();
                /*
                String url = getActivity().getFilesDir() + File.separator + TMP_PATH;
                String path = uri == null ? url : uri.getPath();
                Bitmap photo1 = BitmapFactory.decodeFile(path);
                if (photo1 == null) {
                    Toast.makeText(getActivity(), "没有数据", Toast.LENGTH_LONG).show();
                } else {
                    headImage.setImageBitmap(photo1);
                }
                */

                // ClipImageActivity.startActivity(this, path, CLIP_RESULT);

                Bitmap photo = null;
                if (uri != null) {
                    photo = BitmapFactory.decodeFile(uri.getPath());
                }
                if (photo == null) {
                    Bundle bundle = data == null ? null : data.getExtras();
                    if (bundle != null) {
                        photo = (Bitmap) bundle.get("data");
                    }
                }

                if (photo != null) {
                    // headImage.setImageBitmap(photo);
                    ClipImageActivity.startActivity(this, photo, CLIP_RESULT);
                }
                break;
            case ALBUM_PICTURE:
                uri = data == null ? null : data.getData();
                String path = null;
                if (uri != null) {
                    if ("file".equals(uri.getScheme())) {
                        path = uri.getPath();
                    } else {
                        String[] projection = {MediaStore.Images.Media.DATA};
                        Cursor cursor = getActivity().getContentResolver().query(uri, projection, null, null, null);
                        cursor.moveToFirst();
                        path = cursor.getString(cursor.getColumnIndex(projection[0]));
                    }
                    if (path != null) {
                        ClipImageActivity.startActivity(this, path, CLIP_RESULT);
                    } else {
                        Bitmap bitmap = null;

                        try {
                            bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
                        } catch (Exception e) {

                        }

                        if (bitmap != null) {
                            ClipImageActivity.startActivity(this, bitmap, CLIP_RESULT);
                        } else {
                            Toast.makeText(getActivity(), "获取图片失败!", Toast.LENGTH_LONG).show();
                        }
                    }
                } else {
                    Toast.makeText(getActivity(), "获取图片失败!", Toast.LENGTH_LONG).show();
                }
                break;
            case CLIP_RESULT:
                path = data == null ? null : data.getStringExtra(ClipImageActivity.RESULT_PATH);

                if (path == null || path.length() < 1) {
                    Toast.makeText(getActivity(), "图片截取失败", Toast.LENGTH_LONG).show();
                } else  {
                    photo = BitmapFactory.decodeFile(path);
                    if (photo != null) {
                        headImage.setImageBitmap(photo);
                        File file = new File(path);

                        TypedFile typedFile = new TypedFile("application/octet-stream", file);

                        RestAdapter restAdapter = RetrofitNetworkService.makeAsyncRestAdapter();
                        serviceHandler.uploadHeader(restAdapter, notifyHandler, PrefUtils.getUserId(getActivity()), typedFile, "test.jpg", "jpeg", UPLOAD_HEADER_IMAGE);
                    } else {
                        Toast.makeText(getActivity(), "图片截取失败", Toast.LENGTH_LONG).show();
                    }
                }

                break;
        }
    }
}
